package com.hyc.myvideo.ui.activity.my;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;

import com.acmenxd.toaster.Toaster;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.hyc.myvideo.R;
import com.hyc.myvideo.data.api.constants.Constants;
import com.hyc.myvideo.data.api.model.BaseResult;
import com.hyc.myvideo.data.api.model.UserInfo;
import com.hyc.myvideo.ui.base.BaseFActivity;
import com.hyc.myvideo.utils.UserTokenCache;
import com.hyc.myvideo.widget.ClearEditText;
import com.hyc.utils.AppNetworkMgr;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import timber.log.Timber;

/**
 * 登录
 * @author gyb
 * @version 1.0
 * @created 2017/07/14
 */
public class LoginActivity extends BaseFActivity{
    /**
     * 获取输入账号
     */
    @BindView(R.id.e_account_id)
    ClearEditText editTextPhone;
    /**
     * 获取输入密码
     */
    @BindView(R.id.e_account_password_id)
    ClearEditText editTextPassword;
    /**
     * 登录按钮
     */
    @BindView(R.id.bu_login_id)
    Button buttonLogin;
    /**
     * 第三方登录授权
     */
    private UMShareAPI mShareAPI;
    @Override
    public int getContentViewId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initView() {
        setLeftBtnClick(true, getStr(R.string.home_head_login));
        setButtonSubmit(false);
        editTextPhone.addTextChangedListener(textWatcherPhone);
        editTextPassword.addTextChangedListener(textWatcherPassword);
        mShareAPI = UMShareAPI.get(this);
    }

    @Override
    protected void initData() {
        editTextPhone.setText("13888888888");
        editTextPassword.setText("123123");
    }


    @OnClick({
            R.id.bu_login_id,
            R.id.bu_registered_id,
            R.id.tv_forget_password_id,
            R.id.tv_login_qq,
            R.id.tv_login_weix,
            R.id.tv_login_weibo
    })
    public void onClicks(View view) {
        switch (view.getId()) {
            /**登录*/
            case R.id.bu_login_id:
                api.userLogin(getBEDstr(editTextPhone), getBEDstr(editTextPassword));
                break;
            /**注册*/
            case R.id.bu_registered_id:
                startActivityForResult(new Intent(this, RegisteredActivity.class), Constants.RESULT_CODE);
                break;
            /**忘记密码*/
            case R.id.tv_forget_password_id:
                startActivity(new Intent(this, ForgetActivity.class));
                break;
            /**qq*/
            case R.id.tv_login_qq:
                LogintRipartite(SHARE_MEDIA.QQ);
                break;
            /**weix*/
            case R.id.tv_login_weix:
                LogintRipartite(SHARE_MEDIA.WEIXIN);
                break;
            /**weibo*/
            case R.id.tv_login_weibo:
                LogintRipartite(SHARE_MEDIA.SINA);
                break;
        }
    }



    /***
     * 获取第第三登录授权或用户数据
     * @param platform
     */
    private void LogintRipartite(final SHARE_MEDIA platform) {
        if (AppNetworkMgr.isAvailable(this)) {
            //判断的是否安装客户端
            if (mShareAPI.isInstall(this, platform)) {
                mShareAPI.doOauthVerify(this, platform, new UMAuthListener() {
                    /**
                     * @desc 授权开始的回调
                     * @param share_media 平台名称
                     */
                    @Override
                    public void onStart(SHARE_MEDIA share_media) {
                    }
                    /**
                     * @desc 授权成功的回调
                     * @param share_media 平台名称
                     * @param i 行为序号，开发者用不上
                     * @param map 用户资料返回
                     */
                    @Override
                    public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                        mShareAPI.getPlatformInfo(LoginActivity.this, platform, new UMAuthListener() {
                            @Override
                            public void onStart(SHARE_MEDIA share_media) {
                            }

                            @Override
                            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                            }
                            @Override
                            public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {

                            }

                            @Override
                            public void onCancel(SHARE_MEDIA share_media, int i) {

                            }
                        });
                    }

                    /**
                     * @desc 授权失败的回调
                     * @param share_media 平台名称
                     * @param i 行为序号，开发者用不上
                     * @param t 错误原因
                     */
                    @Override
                    public void onError(SHARE_MEDIA share_media, int i, Throwable t) {

                    }

                    /**
                     * @desc 授权取消的回调
                     * @param share_media 平台名称
                     * @param i 行为序号，开发者用不上
                     */
                    @Override
                    public void onCancel(SHARE_MEDIA share_media, int i) {

                    }
                });
            } else {
                Toaster.show("未安装客户端!");
            }
        } else {
            Toaster.show("无网络!");
        }
    }


    /***
     * 设置提交按钮状态
     * @param isClickable
     */
    private void setButtonSubmit(boolean isClickable) {
        buttonLogin.setClickable(isClickable);
        if (isClickable) {
            buttonLogin.setBackgroundResource(R.drawable.button_shape_35);
        } else {
            buttonLogin.setBackgroundResource(R.drawable.button_shape_35_1);

        }
    }

    /***
     * 监听账号输入
     */
    TextWatcher textWatcherPhone = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
        @Override
        public void afterTextChanged(Editable s) {
            int num = s.toString().length();
            if (num >= 11 && getBEDstr(editTextPassword).length() >= 6) {
                setButtonSubmit(true);
            } else {
                setButtonSubmit(false);
            }
        }
    };
    /***
     * 监听密码输入
     */
    TextWatcher textWatcherPassword = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            int num = s.toString().length();
            if (num >= 6) {
                if (getBEDstr(editTextPhone).length() >= 11) {
                    setButtonSubmit(true);
                }
            } else {
                setButtonSubmit(false);
            }

        }
    };

    @Override
    protected void oNext(String r, String method) {
        BaseResult<UserInfo> result = JSONObject.parseObject(r, new TypeReference<BaseResult<UserInfo>>(){});
        //账号登录
        if(method.equalsIgnoreCase(Constants.API_LOGIN)){
            if(result.isCode()){
                this.finish();
                UserInfo userInfo = result.getResult();
                userInfo.setLogin(true);//标记登录
                UserTokenCache.USER_ID.putValue(userInfo.getUser_id(),appContext);
                UserTokenCache.USER_TOKEN.putValue(userInfo.getUser_token(),appContext);
                appContext.setUserInfo(userInfo);
                if(mCallback != null){
                    mCallback.onLogin();
                }
            }
        }
        //第三方登录
        if(method.equalsIgnoreCase(Constants.API_LOGIN_TRIPARTITE)){

        }
        Toaster.show(result.getMsg());
    }

    @Override
    protected void oError() {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mShareAPI.onActivityResult(requestCode, resultCode, data);
        switch (resultCode){
            case Constants.RESULT_CODE:
                try {
                    Bundle bundle = data.getExtras();
                    String account = bundle.getString("account");
                    editTextPhone.setText(account);
                    //移动光标到末尾
                    editTextPhone.setSelection(editTextPhone.getText().toString().trim().length());
                } catch (Exception e) {
                    Timber.e(e,"注册成功返回登录");
                }
                break;
        }
    }

    static LoginCallback mCallback;
    public interface LoginCallback {
        void onLogin();
    }
    public static boolean checkLogin(Context context, LoginCallback callback) {
         mCallback = callback;
        boolean b = false;
        //此处检查当前的登录状态
        if (!userInfo.isLogin()) {
            Intent intent = new Intent(context, LoginActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
            b = false;
        }else {
            callback.onLogin();
            b = true;
        }
        return b;
    }

}
